package com.xtwroot.android.photogallery;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import java.util.List;

/********************************************************************************
 * using for:
 * 丁酉鸡年正月 2017/03/01 21:58
 * @author 西唐王, xtwyzh@gmail.com,xtwroot.com
 * xtwroot Copyrights (c) 2017. All rights reserved.
 ********************************************************************************/

public class PollService extends IntentService
{
    private static final String TAG = "PollService";
    public static final String ACTION_SHOW_NOTIFICATION = "com.xtwroot.android.photogallery.SHOW_NOTIFICATION";
    public static final String PREM_PEIVATE = "com.xtwroot.android.photogallery.PRIVATE";
    public static final String RESULT_CODE = "RESULR_CODE";
    public static final String NOTIFICATION = "NOTIFICATION";


    private static final long POLL_INTERVAL = AlarmManager.INTERVAL_FIFTEEN_MINUTES; // 60 seconds

    public static Intent newIntent(Context context)
    {
        return new Intent(context,PollService.class);
    }

    public PollService(){
        super(TAG);
    }

    public static boolean isServiceAlarmOn(Context context)
    {
        Intent i = PollService.newIntent(context);
        PendingIntent pi = PendingIntent.getService(context,0,i,PendingIntent.FLAG_NO_CREATE);
        return pi != null;
    }

    public static void setServiceAlarm(Context context,boolean isOn){
        Intent i = PollService.newIntent(context);
        PendingIntent pi = PendingIntent.getService(context,0,i,0);

        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

        if(isOn)
            alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),POLL_INTERVAL,pi);
        else
        {
            alarmManager.cancel(pi);
            pi.cancel();
        }
        QueryPreferences.setAlarm(context,isOn);
    }

    @Override
    protected void onHandleIntent(Intent intent){
        if(!isNetworkAvailableAndConnected())
            return;

        String query = QueryPreferences.getSoredQuery(this);
        String lastResultId = QueryPreferences.getLastResult(this);
        List<GalleryItem> items;

        if(query == null)
        {
            items = new FlickrFetchr().fetchPhotos();
        }
        else
        {
            items = new FlickrFetchr().searchPhotos(query);
        }
        if(items.size() == 0)
            return;

        String resultId  = items.get(0).getId();
        if(resultId.equals(lastResultId)){
            Log.i(TAG,"Got an old result: " + resultId);
        }
        else{
            Log.i(TAG,"Got a new result: " + resultId);

            Resources resources = getResources();
            Intent i = PhotoGalleryActivity.newIntent(this);
            PendingIntent pi = PendingIntent.getService(this,0,i,0);

            Notification notification = new NotificationCompat.Builder(this)
                    .setTicker(resources.getString(R.string.new_pictures_title))
                    .setSmallIcon(android.R.drawable.ic_menu_report_image)
                    .setContentTitle(resources.getString(R.string.new_pictures_title))
                    .setContentText(resources.getString(R.string.new_pictures_text))
                    .setContentIntent(pi)
                    .setAutoCancel(true)
                    .build();

            showBackgroundNotification(0,notification);
        }

        QueryPreferences.setLastResultId(this,resultId);
    }

    private void showBackgroundNotification(int requestCode,Notification notification){
        Intent i = new Intent(ACTION_SHOW_NOTIFICATION);
        i.putExtra(RESULT_CODE,requestCode);
        i.putExtra(NOTIFICATION,notification);
        sendOrderedBroadcast(i,PREM_PEIVATE,null,null, Activity.RESULT_OK,null,null);
    }

    private boolean isNetworkAvailableAndConnected(){
        ConnectivityManager cm = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);

        boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
        boolean isNetworkConnected = isNetworkAvailable && cm.getActiveNetworkInfo().isConnected();
        return isNetworkConnected;
    }

}
